package com.imooc.service.impl;

import com.imooc.service.UserPermissionService;
import org.casbin.jcasbin.main.Enforcer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserPermissionServiceImpl implements UserPermissionService {
    @Autowired
    private Enforcer enforcer;

    @Override
    public boolean checkPermission(String userId, String resource, String action) {
        // 这里传递userId, resource, action来进行权限检查
        // Casbin会自动将这3个参数与策略的4个参数进行匹配
        return enforcer.enforce(userId, resource, action);
    }

    @Override
    public boolean addPolicy(String userId, String resource, String action) {
        // 添加策略时必须包含第四个参数(效果)，根据模型定义为"allow"或"deny"
        return enforcer.addPolicy(userId, resource, action, "allow");
    }

    @Override
    public boolean removePolicy(String userId, String resource, String action) {
        // 删除策略时也必须匹配4个参数
        return enforcer.removePolicy(userId, resource, action, "allow");
    }

    @Override
    public List<List<String>> getPermissionsForUser(String userId) {
        return enforcer.getPermissionsForUser(userId);
    }

    @Override
    public List<List<String>> getAllPolicies() {
        return enforcer.getPolicy();
    }

    @Override
    public boolean addRoleForUser(String userId, String role) {
        return enforcer.addRoleForUser(userId, role);
    }

    @Override
    public List<String> getRolesForUser(String userId) {
        return enforcer.getRolesForUser(userId);
    }

    @Override
    public boolean deleteRoleForUser(String userId, String role) {
        return enforcer.deleteRoleForUser(userId, role);
    }

    @Override
    public boolean deletePermissionsForUser(String userId) {
        return enforcer.deletePermissionsForUser(userId);
    }
}